package com.csx.saas.platform.auth.grant;

import com.csx.basic.base.R;
import com.csx.basic.context.ContextConstants;
import com.csx.basic.exception.code.ExceptionCode;
import com.csx.basic.jwt.TokenUtil;
import com.csx.basic.jwt.model.AuthInfo;
import com.csx.basic.utils.BizAssert;
import com.csx.basic.utils.StrHelper;
import com.csx.saas.platform.auth.dto.LoginParamDTO;
import com.csx.saas.platform.system.entity.SystemUser;
import com.csx.saas.platform.system.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.csx.saas.platform.auth.grant.RefreshTokenGranter.GRANT_TYPE;

/**
 * 刷新token
 *
 * @author ChenSongXin
 * @date 2021/2/19 16:53
 */
@Component(GRANT_TYPE)
public class RefreshTokenGranter extends AbstractTokenGranter implements TokenGranter{
    public static final String GRANT_TYPE = "refresh_token";

    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public R<AuthInfo> login(LoginParamDTO loginParam) {
        String grantType = loginParam.getGrantType();
        String refreshTokenStr = loginParam.getRefreshToken();
        if (StrHelper.isAnyBlank(grantType, refreshTokenStr) || !GRANT_TYPE.equals(grantType)) {
            BizAssert.fail("加载用户信息失败");
        }

        AuthInfo authInfo = tokenUtil.parseRefreshToken(refreshTokenStr);
        if (!ContextConstants.REFRESH_TOKEN_KEY.equals(authInfo.getTokenType())) {
            BizAssert.fail("refreshToken无效，无法加载用户信息");
        }

        //查询账号
        SystemUser systemUser = systemUserService.getById(authInfo.getUserId());
        //账号错误
        BizAssert.notNull(systemUser, ExceptionCode.JWT_USER_INVALID);

        //校验账号状态
        if (systemUser.getState().eq("locked")) {
            String msg = "用户被禁用，请联系管理员！";
            BizAssert.fail(msg);
        }
        //创建token
        AuthInfo newAuth = this.createToken(systemUser);
        return R.success(newAuth);
    }
}
